import { computed, ref } from "vue";

// 处理组件焦点
export function useFocus(data, previewRef, callback) {
  // -1表示未选中，索引值>0
  const selectIndex = ref(-1);

  // 最后选中的组件
  const lastSelectBlock = computed(() => data.value.blocks[selectIndex.value]);

  // 取消所有组件的焦点
  const clearBlockFocus = () => {
    data.value.blocks.forEach((block) => (block.focus = false));
  };
  // 找到所有有焦点和无焦点的组件
  const focusData = computed(() => {
    let focus = []; // 保存所有有焦点
    let unfocused = []; // 所有无焦点
    data.value.blocks.forEach((block) => (block.focus ? focus : unfocused).push(block));
    return {
      focus,
      unfocused,
    };
  });
  // 获取焦点
  const blockMousedown = (e, block, index) => {
    // 如果是预览状态，则返回
    if (previewRef.value) return;
    e.preventDefault(); // 阻止默认事件
    e.stopPropagation(); // 事件冒泡也阻止

    if (e.shiftKey) {
      // console.log("按下shift...")
      // block.focus = !block.focus;
      // 找到有焦点和无焦点的组件，当有焦点的组件为1时，则不再取消焦点
      if (focusData.value.focus.length <= 1) {
        // console.log("不再取消焦点")
        block.focus = true;
      } else {
        block.focus = !block.focus;
      }
    } else {
      if (!block.focus) {
        clearBlockFocus(); //清除所有选中的焦点
        block.focus = true;
      }
    }

    // 选中的组件index
    // console.log("选中组件index:", index);
    selectIndex.value = index;

    callback(e);
  };
  // 在画布上空白处点击 取消所有焦点
  const containerMousedown = () => {
    // 预览状态下忽略
    if (previewRef.value) return;
    clearBlockFocus();

    // 全部取消，索引-1
    selectIndex.value = -1;
  };

  return {
    clearBlockFocus,
    containerMousedown,
    blockMousedown,
    focusData,
    selectIndex,
    lastSelectBlock,
  };
}
